import { ElInput } from "element-plus";
import { ElButton } from "element-plus";
import { ElDialog } from "element-plus";
import { createVNode, render } from "vue";
export type DialogOption = {
  title: string;
  content: string;
  footer?: boolean;
  onComfirm?: (option:string) => void;
};
const DialogComponent = defineComponent({
  props: {
    option: {
      type: Object as PropType<DialogOption>,

      default: () => ({}),
    },
  },
  setup(props, { expose }) {
    const { option } = props;

    const state = reactive({
      isShow: false,
      option: option, //
    });
    expose({
      showDialog(option: DialogOption) {
        state.option = option; //没有生成新组件vm的时候可能需要更新option参数
        state.isShow = true;
      },
    });
    const onComfirm = () => {
      state.isShow = false;
      state.option.onComfirm?.(state.option.content);
    };
    return () => {
      return (
        <ElDialog v-model={state.isShow} title={state.option.title} width="30%">
          {{
            default: (
              <ElInput
                type="textarea"
                v-model={state.option.content}
                rows={10}
              ></ElInput>
            ),

            footer: () =>
              state.option.footer && (
                <div>
                  <ElButton type="primary" onClick={onComfirm}>
                    确定
                  </ElButton>
                  <ElButton onClick={() => (state.isShow = false)}>
                    取消
                  </ElButton>
                </div>
              ),
          }}
        </ElDialog>
      );
    };
  },
});

let vm: any;
export function $Dialog(option: DialogOption) {
  //手动挂载组件
  let el = document.createElement("div");
  if (!vm) {
    vm = createVNode(DialogComponent, { option }); //将组件渲染成虚拟节点
    // 将组件渲染到el这个元素上
    render(vm, el);
    document.body.appendChild(el);
  }
  vm.component?.exposed?.showDialog(option);
}
